package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PurchaseUserDao;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.enums.subform.PurchaseTeamEnum;
import com.xbongbong.saas.model.PurchaseUserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service("PurchaseUserModel")
public class PurchaseUserModelImpl implements PurchaseUserModel{
    @Resource
    private PurchaseUserDao purchaseUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer insert(PurchaseUserEntity entity) throws XbbException {
        entity.setAddTime(DateTimeUtil.getInt());
        entity.setUpdateTime(DateTimeUtil.getInt());
        Integer result = purchaseUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity,IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer update(PurchaseUserEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        Integer result = purchaseUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    /**
     * 获取符合查询条件的记录
     *
     * @param param 查询条件
     * @return 符合查询条件的记录
     */
    @Override
    public List<PurchaseUserEntity> findEntitys(Map<String, Object> param) {
        return purchaseUserDao.findEntitys(param);
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return purchaseUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    /**
     * 保存
     *
     * @param purchaseUserEntity 实体
     * @return 成功
     * @throws XbbException 异常
     */
    @Override
    public Integer save(PurchaseUserEntity purchaseUserEntity) throws XbbException {
        if (purchaseUserEntity.getId() == null || purchaseUserEntity.getId().equals(0L)) {
            return insert(purchaseUserEntity);
        } else {
            return update(purchaseUserEntity);
        }
    }

    /**
     * 查询协同团队基础列表
     *
     * @param map 参数
     * @return 团队
     */
    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return purchaseUserDao.findBaseEntitys(map);
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return purchaseUserDao.getDataIdList(corpid,isMain,userId);
    }

    @Override
    public PurchaseUserEntity getByKey(Long teamUserId, String corpid) {
        return purchaseUserDao.getByKey(teamUserId,corpid);
    }

    @Override
    public void delete(PurchaseUserEntity purchaseUserEntity) throws XbbException {
        purchaseUserEntity.setDel(1);
        purchaseUserEntity.setUpdateTime((long) DateUtil.getInt());
        purchaseUserDao.update(purchaseUserEntity);
        paasEsModel.delete(purchaseUserEntity.getId(), purchaseUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM,purchaseUserEntity.getDataId());
    }

    @Override
    public void insertBatch(List<PurchaseUserEntity> purchaseUserEntityList, boolean isImport) throws XbbException {
        purchaseUserDao.insertBatch(purchaseUserEntityList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM, purchaseUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM));
        }

//        for (PurchaseUserEntity purchaseUserEntity : purchaseUserEntityList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//            insertDTO.setEsId(purchaseUserEntity.getCorpid() + "_" + purchaseUserEntity.getId());
//            insertDTO.setParent(purchaseUserEntity.getCorpid() + "_" + purchaseUserEntity.getDataId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(purchaseUserEntity, false, true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
//            insertDTOList.add(insertDTO);
//        }
        if (isImport) {
            paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertDTOList);
        }
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        purchaseUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(PurchaseTeamEnum.getAttrConnectData(PurchaseTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        purchaseUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(PurchaseTeamEnum.getAttrConnectData(PurchaseTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public List<PurchaseUserEntity> getPurchaseUserListByPurchaseId(String corpid, Long purchaseId, Integer isMain) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("purchaseId", purchaseId);
        if (isMain != null) {
            param.put("isMain", isMain);
        }
        return findEntitys(param);
    }

    /**
     * Description: 获取合同负责人或协同人id list
     *
     * @param corpid     公司id
     * @param purchaseId 采购合同id
     * @param isMain     是否为负责人 1负责人 0 协同人
     * @return java.util.List<java.lang.String>
     * @author chenshan
     * @date 2019/3/6 17:15
     * @since v1.0
     */
    @Override
    public List<String> getPurchaseUserIdList(String corpid, Long purchaseId, Integer isMain) {
        return purchaseUserDao.getPurchaseUserIdList(corpid, purchaseId, isMain);
    }

    @Override
    public List<String> getPurchaseUserIdList(String corpid, List<String> purchaseIds, Integer isMain) {
        return purchaseUserDao.getPurchaseUserIdListByIn(corpid, purchaseIds, isMain);
    }

    @Override
    public Map<Long, String> batchDeleteById(String corpid, List<Long> removeIdList) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("idIn",removeIdList);
        List<PurchaseUserEntity> purchaseUserEntityList = findEntitys(map);
        purchaseUserDao.batchDeleteById(corpid,removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<Long,String> purchaseUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PurchaseUserEntity entity : purchaseUserEntityList){
            purchaseUserMap.put(entity.getDataId(),entity.getUserId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return purchaseUserMap;
    }

    @Override
    public void deleteBatchUser(List<PurchaseUserEntity> purchaseUserEntityList, String corpid, Integer del) throws XbbException {
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(StringConstant.DEL, del);
        for (PurchaseUserEntity entity : purchaseUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        deleteBatch(idList,corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }

    private Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException{
        return purchaseUserDao.deleteBatch(list, corpid, del);
    }

    @Override
    public Integer updateBatch(List<PurchaseUserEntity> list, String corpid) throws XbbException {
        Integer result = purchaseUserDao.updateBatch(list, corpid);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM, list);
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM));
        }
        paasEsModel.updateBatch(insertList);
        return result;
    }

    @Override
    public void deletByDataIds(List<Long> dataIds, String corpid) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("purchaseIdIn", dataIds);
        List<PurchaseUserEntity> purchaseUserEntities = findEntitys(map);
        purchaseUserDao.deleteByDataIds(dataIds, corpid);
        for (PurchaseUserEntity entity : purchaseUserEntities) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM,entity.getDataId());
        }

    }


    /**
     *
     * @Description: 编辑团队成员标签
     * @param purchaseUserEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/17  14:20
     */
    @Override
    public void editLabel(PurchaseUserEntity purchaseUserEntity) throws XbbException {
        updateFormTeam(purchaseUserEntity);
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param purchaseUserEntity
     */
    @Override
    public void updateEditFormPer(PurchaseUserEntity purchaseUserEntity) throws XbbException {
        updateFormTeam(purchaseUserEntity);
    }


    private void updateFormTeam(PurchaseUserEntity purchaseUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        purchaseUserEntity.setUpdateTime(updateTime);
        purchaseUserDao.update(purchaseUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = purchaseUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + purchaseUserEntity.getId());
        insertDTO.setParent(corpid + "_" + purchaseUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        purchaseUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }
}
